﻿using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EWSEditor.CRM.Forms
{
    public partial class LastSyncDetailsForm : Form
    {

        private string _exchangeSyncStateXml;
        private ExchangeService _exchangeService;
        public LastSyncDetailsForm(ExchangeService service)
        {
            InitializeComponent();
            btnSyncNow.Enabled = false;
            _exchangeService = service;
            _exchangeSyncStateXml = ExchangeSyncStateXml.GetCurrentExchangeSyncStateXml();
            SetupListView();
            PopulateFormDetails();
        }

        private void PopulateFormDetails()
        {
            if (string.IsNullOrEmpty(_exchangeSyncStateXml))
            {
                MessageBox.Show("No ExchangeSyncStateXml found. You may need to Test and Enable the mailbox for ACT synchronization.");
                return;
            }

            ExchangeSyncStateXml xml = new ExchangeSyncStateXml(_exchangeSyncStateXml);
            txtClientId.Text = xml.ClientId.ToString();
            txtLastSyncCrmItemFinderCreateChangeCount.Text = xml.LastSyncCrmItemFinderCreateChangeCount.ToString();
            txtLastSyncCrmItemFinderDeleteChangeCount.Text = xml.LastSyncCrmItemFinderDeleteChangeCount.ToString();
            txtLastSyncCrmItemFinderUpdateChangeCount.Text = xml.LastSyncCrmItemFinderUpdateChangeCount.ToString();
            txtLastSyncEndTime.Text = xml.LastSyncEndTime.ToString();
            txtLastSyncExchangeItemFinderCreateChangeCount.Text = xml.LastSyncExchangeItemFinderCreateChangeCount.ToString();
            txtLastSyncExchangeItemFinderUpdateChangeCount.Text = xml.LastSyncExchangeItemFinderUpdateChangeCount.ToString();
            txtLastSyncExchangeItemFinderDeleteChangeCount.Text = xml.LastSyncExchangeItemFinderDeleteChangeCount.ToString();
            txtLastSyncItemRetrievedTime.Text = xml.LastSyncItemRetrievedTime.ToString();
            txtLastSyncStartTime.Text = xml.LastSyncStartTime.ToString();
            txtRebuildIdMapping.Text = xml.RebuildIdMapping.ToString();
            txtSubscriptionId.Text = xml.SubscriptionId.ToString();
        }

        private void SetupListView()
        {
            if (string.IsNullOrEmpty(_exchangeSyncStateXml))
            {
                return;
            }
            List<ExchangeFolderSyncState> LastFolderItems = ExchangeSyncStateXml.GetExchangeFolderSyncStateCollectionFromXpath("ExchangeSyncState/LastFolderItemsSyncStates", _exchangeSyncStateXml);
            List<ExchangeFolderSyncState> LastFolderHierarchy = ExchangeSyncStateXml.GetExchangeFolderSyncStateCollectionFromXpath("ExchangeSyncState/LastFolderHierarchySyncStates", _exchangeSyncStateXml);
            PopulateListView(LastFolderHierarchy, 0);
            PopulateListView(LastFolderItems, 1);
           
        }

        private void PopulateListView(List<ExchangeFolderSyncState> syncStates, int group)
        {
            int idx = lstvwSyncStates.Items.Count;
           
            foreach (ExchangeFolderSyncState folderitem in syncStates)
            {
                ListViewItem item = new ListViewItem();
                item.Tag = folderitem;
                item.Text = folderitem.FolderName;
                item.SubItems.Add(folderitem.FolderClass);
                item.SubItems.Add(folderitem.FolderId);
                item.SubItems.Add(folderitem.SyncState);
                lstvwSyncStates.Items.Add(item);
                lstvwSyncStates.Items[idx].Group = lstvwSyncStates.Groups[group];
                idx = idx + 1;
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void btnSyncNow_Click(object sender, EventArgs e)
        {
            if (lstvwSyncStates.SelectedItems.Count != 1)
            {
                MessageBox.Show("Please select a single folder to perform the synchronization test.");
                return;
            }

            try
            {
                if (((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).FolderId == "0" || ((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).FolderId == "1" || ((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).FolderId == "9")
                {
                    string FolderId = EWSHelpers.GetFolderIdFromInt(((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).FolderId, _exchangeService);
                    SyncFolderItemsForm.ShowDynamicsForm(_exchangeService, FolderId, ((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).SyncState);
                    return;
                }

                SyncFolderItemsForm.ShowDynamicsForm(_exchangeService, ((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).FolderId, ((ExchangeFolderSyncState)lstvwSyncStates.SelectedItems[0].Tag).SyncState);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
            }
        }

        private void lstvwSyncStates_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CrmOrgMailboxCache.SupportMode)
            {
                btnSyncNow.Enabled = false;
                return;
            }

            if (lstvwSyncStates.SelectedItems.Count == 0)
            {
                return;
            }

            if (lstvwSyncStates.Groups[1] == lstvwSyncStates.SelectedItems[0].Group)
            {
                btnSyncNow.Enabled = true;
            }
            else
            {
                btnSyncNow.Enabled = false;
            }
        }

        private void lstvwSyncStates_KeyUp(object sender, KeyEventArgs e)
        {
            if (sender != lstvwSyncStates) return;

            if (e.Control && e.KeyCode == Keys.C)
                CopySelectedValuesToClipboard();
        }

        private void CopySelectedValuesToClipboard()
        {
            var builder = new StringBuilder();
            foreach (ListViewItem item in lstvwSyncStates.SelectedItems)
            {
                builder.AppendLine(item.SubItems[0].Text);
                builder.AppendLine(item.SubItems[1].Text);
                builder.AppendLine(item.SubItems[2].Text);
                builder.AppendLine(item.SubItems[3].Text);
            }

            Clipboard.SetText(builder.ToString());
        }
    }
}
